<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
import {
  ElectricalControlClassification,
  ElectricalControlMaterial,
  ElectricalControlMaterialListParam
} from "@/api/electrical/type";
import {
  addMaterialApi,
  editMaterialApi,
  deleteMaterialApi,
  getMaterialListApi,
  getSimpleClassificationListApi
} from "@/api/electrical";
import {Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import TreeSelect from "@/components/TreeSelect/index.vue";

// ----------------------- 组件状态定义 -----------------------
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 分类列表
const classificationList = ref<ElectricalControlClassification[]>([])

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<ElectricalControlMaterialListParam>({
  classificationId: undefined,
  name: undefined,
  brand: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.classificationId = undefined
  searchForm.name = undefined
  searchForm.brand = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getMaterialListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getClassificationList = async () => {
  try {
    let res = await getSimpleClassificationListApi()
    if (res && res.data) {
      classificationList.value = res.data
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 通过分类ID获取分类名称
const getClassificationName = (id: number) => {
  const classification = classificationList.value.find(item => item.id === id)
  return classification ? classification.name : '--'
}

// ----------------------- 新增/编辑表单相关 -----------------------
const addFormRef = ref<FormInstance>()
const addForm = reactive<ElectricalControlMaterial>({
  id: undefined,
  classificationId: undefined,
  name: undefined,
  specification: undefined,
  price: undefined,
  brand: undefined,
  remark: undefined,
  priceTwo: undefined,
  premium: undefined
})

// 表单校验规则
const rules = {
  classificationId: [{required: true, message: '请选择分类', trigger: 'change'}],
  name: [{required: true, message: '请输入材料名称', trigger: 'blur'}],
  specification: [{required: true, message: '请输入规格型号', trigger: 'blur'}],
}

// 打开新增弹框
const openAdd = () => {
  dialog.title = '新增材料'
  dialog.width = 600
  dialog.height = 450
  onShow()
}

// 打开编辑弹框
const openEdit = (row: ElectricalControlMaterial) => {
  dialog.title = '编辑材料'
  dialog.width = 600
  dialog.height = 450
  nextTick(() => {
    Object.assign(addForm, row)
  })
  onShow()
}

// 关闭弹框
const closeDialog = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    id: undefined,
    classificationId: undefined,
    name: undefined,
    specification: undefined,
    price: undefined,
    priceTwo: undefined,
    premium: undefined,
    brand: undefined,
    remark: undefined
  })
  onClose()
}

// 提交表单
const submit = async () => {
  await addFormRef.value?.validate()
  try {
    let res;
    if (addForm.id) {
      res = await editMaterialApi(addForm)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
        getTableData()
        closeDialog()
      } else {
        ElMessage.error(res.message || '编辑失败')
      }
    } else {
      res = await addMaterialApi(addForm)
      if (res.code === 200) {
        ElMessage.success('新增成功')
        getTableData()
        closeDialog()
      } else {
        ElMessage.error(res.message || '新增失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// ----------------------- 删除相关 -----------------------
const deleteOne = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除该材料吗？')
  if (confirm) {
    try {
      await deleteMaterialApi(id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// ----------------------- 左侧筛选树形数据处理 -----------------------
// 当前选中的分类ID，用于树形筛选
const currentCategoryId = ref<number>()


// ----------------------- 左侧筛选树形数据处理 -----------------------
// 定义树节点类型
interface TreeNode {
  id: string
  name: string
  parentId: string
  children: TreeNode[]
}

// 左侧筛选树形数据
const treeData = ref<TreeNode[]>([])

/**
 * 获取左侧筛选树形数据
 */
const getTreeData = async () => {
  try {
    const res = await getSimpleClassificationListApi()
    if (res?.data) {
      treeData.value = handleTree(res.data)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}

/**
 * 处理左侧筛选树形结构
 * @param data 原始数据
 * @returns 处理后的树形数据，包含虚拟顶级节点
 */
const handleTree = (data: TreeNode[]): TreeNode[] => {
  const map = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  // 创建虚拟的顶级节点
  const rootNode: TreeNode = {
    id: '-1',
    name: '全部分类',
    parentId: '',
    children: [],
  }

  // 初始化映射表
  data.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.id)!
    if (item.parentId === '0') {
      rootNode.children.push(node)
    } else {
      const parent = map.get(item.parentId)
      if (parent) {
        parent.children.push(node)
      }
    }
  })

  result.push(rootNode)
  return result
}
/**
 * 树节点点击事件处理
 */
const handleTreeNodeClick = async (data: any) => {
  // 处理虚拟顶级节点点击事件
  if (data.id === '-1') {
    currentCategoryId.value = undefined;
    searchForm.classificationId = undefined;
  } else {
    currentCategoryId.value = data.id;
    searchForm.classificationId = data.id;
  }
  // 重置分页
  paginationData.currentPage = 1;
  await getTableData();
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  // 获取左侧树形菜单数据
  getTreeData()
  // 获取分类列表（用于下拉框）
  getClassificationList()
  // 获取表格数据
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="process-main">
    <div class="main-container">
      <el-row :gutter="20">
        <!-- 左侧树形菜单 -->
        <el-col :span="4">
          <el-card class="tree-card" shadow="hover">
            <div class="tree-header">
              <i class="el-icon-menu"></i>
              <span>电器分类列表</span>
            </div>
            <TreeSelect
              :data="treeData"
              :props="{
                children: 'children',
                label: 'name'
              }"
              placeholder="请输入分类名称"
              @node-click="handleTreeNodeClick"
              class="process-tree"
            />
          </el-card>
        </el-col>

        <!-- 右侧内容区 -->
        <el-col :span="20">
          <!-- 查询表单区域 -->
          <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="searchForm" class="search-form">
              <el-form-item label="材料名称">
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入材料名称"
                  clearable
                />
              </el-form-item>

              <el-form-item label="品牌">
                <el-input
                  v-model="searchForm.brand"
                  placeholder="请输入品牌"
                  clearable
                />
              </el-form-item>

              <el-form-item class="search-buttons">
                <el-button type="primary" :icon="Search" @click="search" class="search-btn">
                  查询
                </el-button>
                <el-button :icon="Refresh" @click="reset" class="reset-btn">
                  重置
                </el-button>
                <el-button type="success" :icon="Plus" @click="openAdd" class="add-btn">
                  新增
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 表格区域 -->
          <el-card class="table-card" shadow="hover">
            <el-table
              v-loading="loading"
              :data="tableData"
              border
              :height="tableHeight"
              class="data-table"
            >
              <el-table-column type="index" label="序号" width="60" align="center"/>
              <el-table-column prop="classificationId" label="所属分类" min-width="120" align="center">
                <template #default="scope">
                  {{ getClassificationName(scope.row.classificationId) }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="材料名称" min-width="120" align="center"/>
              <el-table-column prop="specification" label="型号规格" min-width="120" show-overflow-tooltip align="center"/>
              <el-table-column prop="brand" label="品牌" min-width="100" align="center"/>
              <el-table-column prop="price" label="单价" min-width="100" align="center">
                <template #default="scope">
                  <span class="price-value">{{ scope.row.price ? `¥${scope.row.price.toFixed(2)}` : '--' }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="priceTwo" label="单价2" min-width="100" align="center">
                <template #default="scope">
                  <span class="price-value">{{ scope.row.priceTwo ? `¥${scope.row.priceTwo.toFixed(2)}` : '--' }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="premium" label="溢价" min-width="100" align="center"/>

              <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip align="center"/>
              <el-table-column label="操作" width="160" fixed="right" align="center">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button type="primary" size="small" :icon="Edit" @click="openEdit(scope.row)" class="edit-btn">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" :icon="Delete" @click="deleteOne(scope.row.id)" class="delete-btn">
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              v-model:current-page="paginationData.currentPage"
              v-model:page-size="paginationData.pageSize"
              :page-sizes="[10, 20, 50]"
              :total="paginationData.total"
              layout="total, sizes, prev, pager, next"
              class="pagination"
              @size-change="getTableData"
              @current-change="getTableData"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :width="dialog.width"
      :visible="dialog.visible"
      :height="dialog.height"
      @onClose="closeDialog"
      @onConfirm="submit"
    >
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="addFormRef"
            :model="addForm"
            :rules="rules"
            label-width="90px"
            class="add-form"
          >
            <el-card class="form-card" shadow="never">
              <template #header>
                <div class="form-header">
                  <span>基本信息</span>
                </div>
              </template>
              <el-form-item label="所属分类" prop="classificationId">
                <el-select
                  v-model="addForm.classificationId"
                  placeholder="请选择分类"
                  class="full-width"
                >
                  <el-option
                    v-for="item in classificationList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="材料名称" prop="name">
                <el-input v-model="addForm.name" placeholder="请输入材料名称"/>
              </el-form-item>
              <el-form-item label="型号规格" prop="specification">
                <el-input v-model="addForm.specification" placeholder="请输入型号规格"/>
              </el-form-item>
              <el-form-item label="单价" prop="price">
                <el-input-number v-model="addForm.price" :precision="2" :min="0" class="full-width" placeholder="请输入单价"/>
              </el-form-item>
              <el-form-item label="单价2" prop="priceTwo">
                <el-input-number v-model="addForm.priceTwo" :precision="2" :min="0" class="full-width" placeholder="请输入单价2"/>
              </el-form-item>
              <el-form-item label="溢价" prop="premium">
                <el-input-number v-model="addForm.premium" :precision="2"  class="full-width" placeholder="请输入溢价"/>
              </el-form-item>
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="addForm.brand" placeholder="请输入品牌"/>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="addForm.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入备注说明"
                />
              </el-form-item>
            </el-card>
          </el-form>
        </div>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.process-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.tree-card {
  border-radius: 8px;
  height: calc(100vh - 100px);

  .tree-header {
    padding: 12px 0;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #67c23a;
    border-bottom: 1px solid #e1f3d8;

    i {
      margin-right: 8px;
    }
  }

  .process-tree {
    height: calc(100vh - 160px);
    overflow: auto;

    :deep(.el-tree-node__content) {
      height: 36px;

      &:hover {
        background-color: #f0f9eb;
      }
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #e1f3d8;
      color: #67c23a;
    }
  }
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;

  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  .el-form-item {
    margin-bottom: 10px;
    margin-right: 16px;
  }

  .search-buttons {
    margin-left: auto;

    .el-button {
      margin-left: 8px;
      transition: all 0.3s;

      &:first-child {
        margin-left: 0;
      }
    }

    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;

      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }

    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;

      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }

    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;

  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;

  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }

  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }

  .price-value {
    font-weight: 600;
    color: #f56c6c;
  }

  .action-buttons {
    display: flex;
    justify-content: center;

    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.dialog-content {
  padding: 10px;
}

.add-form {
  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;

    &:last-child {
      margin-bottom: 0;
    }

    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }

    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
  }

  :deep(.el-input), :deep(.el-select), :deep(.el-input-number) {
    width: 100%;
  }

  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.full-width {
  width: 100%;
}
</style>
